package com.pcjavanet.collect.mes.util;

import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
//import com.sanmina.mesportal.serverinfo.to.MESServerInfo;
//import com.sanmina.mesportal.serverinfo.util.ServerInfoServiceUtil;

/**
 * provide common method for server . attention: all method must use in server
 * side.
 * 
 * @author jack_mo . create date 2008-04-17
 */
public class CommonServerUtil {

	protected static Logger logger = Logger.getLogger(CommonServerUtil.class);

	/** server port */
	private static String HOST_PORT = "";

	private static String SPC_SCHEMA_PREFIX = "spc.";
	
	public static String getSpcSchemaPrefix(){
		return SPC_SCHEMA_PREFIX ;
	}
	
	public static void setSpcSchemaPrefix(String spcSchemaPrefix ){
		SPC_SCHEMA_PREFIX = spcSchemaPrefix ;
	}
	public static void setHostPort(String port) {
		HOST_PORT = port;
	}

	public static String getHostPort() {
		return HOST_PORT;
	}

	public static  int changeStrTimzeToInt( String timezoneOffsetStr ){
		String str = "-00:00:00";
		int lastIndex = timezoneOffsetStr.lastIndexOf(":");
		if ( timezoneOffsetStr.length()<=5) {
			logger.error(" timezoneoffsetStr value:"+timezoneOffsetStr);
		}else{
			str = timezoneOffsetStr.substring(0, lastIndex);
			str = str.replace(":", "");
		}	
		
		int rtv =0;
		try {
			rtv = Integer.parseInt(str);
		}catch (Exception e){
			logger.error(e);
		}
		return rtv ; 
	}
	
	public static long dealMinuteScope(String dateStr ,int minuteRange)
	{
		//dateStr :2008-03-03 14:35:40 
		long returnValue = 0l;
		String days = dateStr.substring(0,10); //2008-03-03
		String time = dateStr.substring(11);	//14:35:40
		Date date = ConvertFormula.parseStrDateUseShortFormate(days);
    	String[] parts = time.split(":");
    	long hours = Long.parseLong(  parts[0]);
    	long minutes = Long.parseLong(  parts[1]);
    	long totalMinute = hours * 60 +minutes;
    	long numbers =0L;
    	int groupingTimeRange =minuteRange;
    	while( totalMinute  >0 )
    	{
    		numbers= numbers+1;
    		totalMinute = totalMinute - groupingTimeRange;
    	}
    	if ( totalMinute <0 )
    		numbers = numbers -1;
    	returnValue =   date.getTime()/1000/60 +  numbers * groupingTimeRange;
		return returnValue;
	}
	
	public static long dealMinuteScope(long aDatetime ,int minuteRange) {
		long minuteRangeSecond = minuteRange*60 ;
		long mulitple = aDatetime/minuteRangeSecond ; 
		return ( mulitple*minuteRange ) ;
	}
	
	public  static boolean judgeFireEvent(long aDateTime , int monitorByTimeRange ) {
		long currentSysSecond = ( System.currentTimeMillis() /1000 );
		long aDatetimeScope = dealMinuteScope( aDateTime , monitorByTimeRange );
		long currentSysSecondScope = dealMinuteScope( currentSysSecond , monitorByTimeRange );
		if ( currentSysSecondScope > aDatetimeScope )
			return true ; 
		else 
			return false ; 
		/*
		long oneDayMisSeconds = 86400000 ; 
		long monitorByTimeRangeSeconds = monitorByTimeRange*60*1000 ;
		long miseconds  = aDateTime * 1000 ; 
		long mulit = miseconds/oneDayMisSeconds;
	 	long dayMiseconds = mulit * oneDayMisSeconds  ; 
	 	long hoursMiseconds = miseconds - dayMiseconds ; 
	 	long mulit2 = hoursMiseconds/monitorByTimeRangeSeconds ; 
	 	long dayMiseconds2 =mulit2 * monitorByTimeRangeSeconds   ;
	 	long end =  dayMiseconds2 + monitorByTimeRangeSeconds    ;
	 	
	 	long currentSysMisec = System.currentTimeMillis() ;
	 	if ( currentSysMisec > ( miseconds + oneDayMisSeconds ) )
	 		return true;
	 	long mulit3 = currentSysMisec/oneDayMisSeconds;
	 	long dayMiseconds3 = mulit3 * oneDayMisSeconds  ; 
	 	long hoursMiseconds3 = currentSysMisec - dayMiseconds3 ;
 
	 	if (hoursMiseconds3 >= end  ) {
	 		return true ;
	 	} else {
	 		return false ;
	 	}*/
	}
	
	public static String getSPCServerTimezoneStr() {
		
/*		if ( LoadCacheUtil.getSystemTimeOffset() .equals("+0000") ){
			ServerInfoDao  serverInfoDao = ( ServerInfoDao ) SpcContext.getApplicationContext().getBean("serverInfoDao");
			String timezoneId = TimeZone.getDefault().getID() ;
			String offsetStr = serverInfoDao.getTimeZoneOffset( timezoneId );
			LoadCacheUtil.setSystemTimeOffset( changeIntTimeToStr ( changeStrTimzeToInt( offsetStr ) ) );
		}
		return LoadCacheUtil.getSystemTimeOffset();*/
		return "";
	}
	
	public static String changeIntTimeToStr(int timeOffset){
		String str="+0000";
		if ( timeOffset<0 ){
			if (  timeOffset >-10) {
				str= "-000"+ Math.abs(timeOffset);
				return str ; 
			}
			if ( timeOffset >-100) {
				str= "-00"+Math.abs(timeOffset);
				return str ;
			}
			if ( timeOffset >-1000 ) {
				str= "-0"+Math.abs(timeOffset);
				return str ;
			}
			if ( timeOffset >-10000 ) {
				str= "-"+Math.abs(timeOffset);
				return str ;
			}			
		}
		if ( timeOffset > 0 ){
			str = ""+timeOffset;
			if ( timeOffset < 10) {
				str= "+000"+ timeOffset;
				return str ; 
			}			
			if ( timeOffset <100) {
				str= "+00"+timeOffset;
				return str ; 
			}
			if ( timeOffset <1000) {
				str= "+0"+timeOffset;
				return str ;
			}
			if (timeOffset <10000 ) {
				str= "+" +timeOffset;
				return str ;
			}
		}		
		return str;
	}
	
	public static String getTimeZoneNumberStr( String netuserId ) {
		return "";
/*		if (netuserId == null || netuserId.equals("")) {
			return "+0000";
		} else {
			HoldCache holdCache = CacheManager.getHoldCacheMap().get( netuserId );
			if (holdCache == null) {
				holdCache = CacheManager.getHoldCacheMap().get(netuserId);
				if (holdCache == null) {
					return  LoadCacheUtil.getSystemTimeOffset()  ;
				}
			}
			return   holdCache.getOffSetStrValue()  ;
		}*/
	}
	
	public static String getSfdcTimeZoneForSql(String netuserId, String who) {
		return " AT TIME ZONE  \'UTC\'  ";
//		if (netuserId == null || netuserId.equals("")) {
//			logger.error(" netuserId is null or  ''  " + who);
//			TimeZone tz = TimeZone.getDefault();
//			int offset = tz.getRawOffset();
//			String text = String.format("%s%02d:%02d", offset >= 0 ? "+" : "-",
//					offset / 3600000, (offset / 60000) % 60);
//			return " AT TIME ZONE \'" + text + "\' ";
//		} else {
//			HoldCache holdCache = CacheManager.getHoldCacheMap().get( netuserId );
//
//			if (holdCache == null) {
//				holdCache = CacheManager.getHoldCacheMap().get(netuserId);
//				if (holdCache == null) {
//					logger.error(" cache can't find  netuserId:" + netuserId
//							+ " in  holdCache. This for getSFDCTimeZone   "
//							+ who);
//					TimeZone tz = TimeZone.getDefault();
//					int offset = tz.getRawOffset();
//					String text = String.format("%s%02d:%02d",
//							offset >= 0 ? "+" : "-", offset / 3600000,
//							(offset / 60000) % 60);
//					return " AT TIME ZONE \'" + text + "\' ";
//				}
//			}
//			return " AT TIME ZONE \'" + holdCache.getSfdcTimeZone() + "\' ";
//		}
 
	}
	
	public static String getSfdcTimeZone(String netuserId, String who) {
		if (netuserId == null || netuserId.equals("")) {
			logger.error(" netuserId is null or  ''  " + who);
			TimeZone tz = TimeZone.getDefault();
			return  tz.getID();
		} else {
//			HoldCache holdCache = CacheManager.getHoldCacheMap().get( netuserId );
//			if (holdCache == null) {
//				holdCache = CacheManager.getHoldCacheMap().get(netuserId);
//				if (holdCache == null) {
//					logger.error(" cache can't find  netuserId:" + netuserId
//							+ " in  holdCache. This for getSFDCTimeZone   "
//							+ who);
//				}
//			}
					TimeZone tz = TimeZone.getDefault();
					return  tz.getID();
//			return   holdCache.getSfdcTimeZone() ;
		}
	}
	
	public static String getSfdcTimeZone(String netUserId) {
		if (netUserId == null || netUserId.equals("")) {
			logger.error(" netuserId is null or  ''  " );
			TimeZone tz = TimeZone.getDefault();
			return  tz.getID();
		} else {
//			HoldCache holdCache = CacheManager.getHoldCacheMap().get( netUserId );
//			if (holdCache == null) {
//				holdCache = CacheManager.getHoldCacheMap().get(netUserId);
//				if (holdCache == null) {
//					logger.error(" cache can't find  netuserId:" + netUserId
//							+ " in  holdCache. This for getSFDCTimeZone   "
//							);
//				}
//			}
			TimeZone tz = TimeZone.getDefault();
			return  tz.getID();
//			return   holdCache.getSfdcTimeZone() ;
		}
		
	}
	
	public static int getSfdcTimeOffsetCompareSpcServer(String netuserId) {
		TimeZone tz  = null ;
		if (netuserId == null || netuserId.equals("")) {
			  tz = TimeZone.getDefault();
		} else {
//			HoldCache holdCache = CacheManager.getHoldCacheMap().get( netuserId );
//			if (holdCache == null) {
//				holdCache = CacheManager.getHoldCacheMap().get(netuserId);
//				if (holdCache == null) {
//				}
//			}
					  tz = TimeZone.getDefault();
//			tz = TimeZone.getTimeZone( holdCache.getSfdcTimeZone() ) ;
		}
		TimeZone localTz = TimeZone.getDefault();
		return (tz.getRawOffset() - localTz.getRawOffset()) ;
	}
	
	public static String changeSecondsToRangeTimeStr(long aDateTime , int monitorByTimeRange , String timezone ) {
		long oneDayMisSeconds = 86400000 ; 
		long localOffset = TimeZone.getDefault().getRawOffset();
		long sfdcOffset = TimeZone.getTimeZone(timezone).getRawOffset();
		long offset = sfdcOffset - localOffset ; 
		long monitorByTimeRangeSeconds = monitorByTimeRange*60*1000 ;
		long miseconds  = aDateTime * 1000  + offset; 
		long mulit = miseconds/oneDayMisSeconds;
	 	long dayMiseconds = mulit * oneDayMisSeconds  ; 
	 	long hoursMiseconds = miseconds - dayMiseconds ; 
	 	long mulit2 = hoursMiseconds/monitorByTimeRangeSeconds ; 
	 	long dayMiseconds2 = dayMiseconds + mulit2 * monitorByTimeRangeSeconds   ;
	 	long end =  dayMiseconds2 + monitorByTimeRangeSeconds    ;
	 	if ( monitorByTimeRange == 1440 )
	 		return ConvertFormula.formateMilsecondToLenStr( dayMiseconds2 ) +" to 23:59:59" ;
	 	else
	 		return ConvertFormula.formateMilsecondToLenStr( dayMiseconds2 ) +" to "+ ConvertFormula.formatDateToTimeStr(end) ;
	}
 
	
	public static void main(String[] args) {
		
		
		
		
		
		
		System.out.println( dealMinuteScope(1397628210, 30));
		System.out.println( dealMinuteScope(1397628283, 30));
		System.out.println( dealMinuteScope(1397628297, 30));
		System.out.println( dealMinuteScope(1397629325, 30));
		System.out.println( dealMinuteScope(1397629347, 30));
		System.out.println( dealMinuteScope(1397629378, 30));
//		System.out.println( ConvertFormula.formateMilsecondToLenStr( (long)1389580252*1000));
//		int monitorByTimeRange =  10 ;
//		System.out.println( changeSecondsToRangeTimeStr( milsecond ,monitorByTimeRange,"America/New_York") );
//		System.out.println( changeSecondsToRangeTimeStr( milsecond ,monitorByTimeRange,"Asia/Shanghai") );
//		System.out.println( changeSecondsToRangeTimeStr( milsecond ,monitorByTimeRange,"") );
//		System.out.println( changeIntTimeToStr(1) );
//		System.out.println( changeIntTimeToStr(11) );
//		System.out.println( changeIntTimeToStr(101) );
//		System.out.println( changeIntTimeToStr(1010) );
//		
//		System.out.println( changeIntTimeToStr(-1) );
//		System.out.println( changeIntTimeToStr(-10) );
//		System.out.println( changeIntTimeToStr(-100) );
//		System.out.println( changeIntTimeToStr(-1001) );
//		TimeZone tz = TimeZone.getDefault();
//		int offset = tz.getRawOffset();
//		String text = String.format("%s%02d:%02d", offset >= 0 ? "+" : "-",
//				offset / 3600000, (offset / 60000) % 60);
//		System.out.println(text);
//		System.out.println( TimeZone.getDefault().getID());
	}

	/**
	 * check data format,if match then return true ,else return false.
	 * 
	 * @param dataStr
	 *            like 2008-05-07
	 * @return if match then return true ,else return false.
	 */
	public static boolean checkDateformat(String dataStr) {
		boolean returnFlag = false;
		Pattern p = Pattern
				.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\-\\s]?((((0?"
						+ "[13578])|(1[02]))[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))"
						+ "|(((0?[469])|(11))[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(30)))|"
						+ "(0?2[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12"
						+ "35679])|([13579][01345789]))[\\-\\-\\s]?((((0?[13578])|(1[02]))"
						+ "[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))"
						+ "[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\-\\s]?((0?["
						+ "1-9])|(1[0-9])|(2[0-8]))))))");
		if (dataStr != null)
			returnFlag = p.matcher(dataStr).matches();
		return returnFlag;
	}

	/**
	 * 
	 * @param colorStr
	 *            like [r=255,g=0,b=0]
	 * @return
	 */
	public static Color parseStrColor(String colorStr) {
		Color rtv = null;
		if (colorStr != null && !colorStr.equals("")) {
			int r = 0;
			int g = 0;
			int b = 0;
			String[] strs = colorStr.split(",");
			r = Integer.parseInt(strs[0].split("=")[1]);
			g = Integer.parseInt(strs[1].split("=")[1]);
			b = Integer.parseInt(strs[2].split("=")[1]);
			rtv = new Color(r, g, b);
		}
		return rtv;
	}

	/**
	 * 
	 * @param color
	 *            Color
	 * @return
	 */
	public static String formatColor(Color color) {
		String rtv = "r=255,g=0,b=0";
		if (color != null) {
			rtv = color.toString();
			int beginIndex = rtv.indexOf("[") + 1;
			int endIndex = rtv.indexOf("]");
			rtv = rtv.substring(beginIndex, endIndex);
		}
		return rtv;
	}

	public static boolean judgeFamily(String partnumber, String familyname) {
		boolean rtv = false;
		if ((partnumber != null && !partnumber.equals(""))
				&& (familyname != null && !familyname.equals(""))) {// p ok, f
																	// ok
																	// ==>choise
																	// p
			rtv = false;
		} else if ((partnumber == null || partnumber.equals(""))
				&& (familyname != null && !familyname.equals(""))) {// p no, f
																	// ok==> f
			rtv = true;
		} else if ((partnumber != null && !partnumber.equals(""))
				&& (familyname == null || familyname.equals(""))) { // p ok,f no
																	// ==> p
			rtv = false;
		}
		return rtv;
	}

	public static Date joinDate(Date dDateTime, int iSecond) {
		SimpleDateFormat sdf = new SimpleDateFormat( ConvertFormula.DATE_FORMAT_LONG );
		String sDateTime = sdf.format(dDateTime);
		String aDateTime[] = sDateTime.substring(0, 10).split("-");
		int iYear = Integer.valueOf(aDateTime[0]).intValue();
		int iMonth = Integer.valueOf(aDateTime[1]).intValue() - 1;
		int iDay = Integer.valueOf(aDateTime[2]).intValue();
		int iHour1 = iSecond / 3600;
		int iMinute1 = (iSecond % 3600) / 60;
		int iSecond1 = iSecond % 3600 % 60;
		GregorianCalendar gc = new GregorianCalendar(iYear, iMonth, iDay,iHour1, iMinute1, iSecond1);
		return gc.getTime();
	}
	
	public static String getSPCServerTimeStr() {
		return  ConvertFormula.formateMilsecondToLenStr( System.currentTimeMillis());
	}
	
	public static String replaceXiegan( String str ) {
		StringBuffer bf = new StringBuffer();
		for( int i=0;i<str.length();i++){
			if ( (int)str.charAt(i) == 92 ) {
				
			} else
			bf.append( str.charAt(i));
		}
		return bf.toString() ; 
	}

}